#!/bin/sh
status="0"
file_check() {
	for file in "$@"; do
		if [ ! -f "$file" ]; then
			logger -s "$0: Missing $file. Please generate and try again."
			status="1"
		fi
	done
}

case "$1" in
	start)
		case "$(nvram get openvpn_cli)" in
			on|enabled|1)
				continue ;;
			off|disabled|0)
				exit 0 ;;
		esac

		SERVER=$(nvram get openvpn_cli_server)
		PROTO=$(nvram get openvpn_cli_proto)
		PORT=$(nvram get openvpn_cli_port)

		[ "$SERVER" ] && {
			SERVER_OPTION="--remote $SERVER --nobind"
		}
		case "$(nvram get openvpn_cli_auth)" in
			cert)
				file_check "/etc/openvpn/certificate.p12"
				AUTH_OPTION="--client --pkcs12 /etc/openvpn/certificate.p12"
			;;
			psk)
				file_check "/etc/openvpn/shared.key"
				AUTH_OPTION="--secret /etc/openvpn/shared.key"
			;;
			pem)
				file_check "/etc/openvpn/ca.crt" "/etc/openvpn/client.crt" "/etc/openvpn/client.key"
				AUTH_OPTION="--client --ca /etc/openvpn/ca.crt --cert /etc/openvpn/client.crt --key /etc/openvpn/client.key"
			;;
			*)
				logger -s "$0: unknown authentication type, aborting!"
				status="1"
			;;
		esac

		if [ "$status" = "0" ]; then
		openvpn --proto  "${PROTO:-udp}"		\
			--port   "${PORT:-1194}"		\
			$SERVER_OPTION				\
			--dev tun				\
			$AUTH_OPTION				\
			--comp-lzo				\
			--daemon				\
			--status /tmp/openvpn-status.log	\
			--verb 3
		fi
	;;
	restart)
		$0 stop
		sleep 3
		$0 start
	;;
	reload)
		killall -SIGHUP openvpn
	;;
	stop)
		killall openvpn 2>/dev/null
	;;
esac
